package com.library.common.util

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager

/**
 * 作者：SimGa
 * 日期：2020/12/20
 * 时间：00:47
 * 包名：com.vitabuybuy.tv.utils
 */
class FragmentUtils {
    companion object {
        fun replaceFragment(
            supportFragmentManager: FragmentManager,
            containerId: Int,
            tag: String
        ) {
            var tempFragment = supportFragmentManager.findFragmentByTag(tag)
            val transaction = supportFragmentManager.beginTransaction()
            if (tempFragment == null) {
                try {
                    tempFragment = Class.forName(tag).newInstance() as Fragment
                    transaction.add(containerId, tempFragment, tag)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            val fragments = supportFragmentManager.fragments
            for (i in fragments.indices) {
                val fragment = fragments[i]
                if (fragment!!.tag == tag) {
                    transaction.show(fragment)
                } else {
                    transaction.hide(fragment)
                }
            }
            transaction.commitAllowingStateLoss()
        }
        fun isFragmentInTracsaction(supportFragmentManager: FragmentManager, tag: String): Boolean {
            val fragments = supportFragmentManager.fragments
            for (i in fragments.indices) {
                return fragments[i].tag == tag
            }
            return false
        }
    }
}